# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import os, calendar
from datetime import date

from pylons import tmpl_context as c, request, url
from pylons.i18n import lazy_ugettext as _
from pylons.controllers.util import redirect
from paste.fileapp import FileApp

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import in_group

from chowa.lib.site.crud import FlatCrudController
from chowa.lib.site.navigation import get_page

from hrms.lib.base import render, Session
from hrms.lib.timesheet import generate_pdf
from hrms.model.person import Employee
from hrms.model.worktime import *

@ControllerProtector(in_group('hrms.administrators'))
class TimesheetController(FlatCrudController):
    __model__ = WorkingMonth
    __edit_columns__ = ['timesheet', 'number', 'salary', 'employee']
    
    def __before__(self, id):
        timesheet = Session.query(Timesheet).get(id)
        c.main_heading = unicode(timesheet)
    
    def index(self, relation, id):
        c.timesheet = Session.query(Timesheet).get(id)
        c.days_in_month = calendar.monthrange(c.timesheet.year,
                                              c.timesheet.month)[1]
        query = Session.query(WorkingMonth).join(Employee)
        query = query.filter(WorkingMonth.timesheet_id == id)
        query = query.order_by(Employee.surname,
                               Employee.name,
                               Employee.patronymic)
        c.employees = get_page(query, items_per_page=20)
        
        return render('/hrms/worktime/timesheet.html')
    
    def pdf(self, id):
        file_path = generate_pdf(id)
        headers = [('Content-Disposition',
                    'attachment; filename=%s' % os.path.basename(file_path))]
        fapp = FileApp(file_path, headers=headers)
        return fapp(request.environ, self.start_response)
    
    def calendar(self, id):
        employee_id = request.params.get('record_id')
        timesheet = Session.query(Timesheet).get(id)
        c.calendar = calendar.monthcalendar(timesheet.year, timesheet.month)
        
        query = Session.query(WorkingMonth)
        
        c.employee = query.get(employee_id)
        c.working_days = {}
        for day in c.employee.days:
            c.working_days[day.day] = day
        
        query = query.join(Employee)
        query = query.filter(WorkingMonth.timesheet_id == id)
        query = query.order_by(Employee.surname,
                               Employee.name,
                               Employee.patronymic)
        employees = query.all()
        index = employees.index(c.employee)
        c.previous = employees[index - 1] if index else None
        c.next = employees[index + 1] if (index + 1) < len(employees) else None
        
        codes = Session.query(WorkingDayCode).all()
        c.codes = [(0, '--')] + [(code.id, code.abbreviation) for code in codes]
        
        days_in_month = calendar.monthrange(timesheet.year, timesheet.month)[1]
        if request.method == 'POST':
            for day in range(1, days_in_month+1):
                query = Session.query(WorkingDay)
                query = query.filter_by(month_id=employee_id,
                                        day=day)
                working_day = query.one()
                working_day.code_id = request.POST.get('code%d' % day)
                hours = request.POST.get('hours%d' % day)
                working_day.hours = hours if hours.isdigit() else None 
            Session.commit()
        return render('/hrms/worktime/calendar.html')
    
    def _after_adding(self, id):
        month = Session.query(WorkingMonth).get(id)
        days_in_month = calendar.monthrange(month.timesheet.year, month.timesheet.month)[1]
        
        i = WorkingDay.__table__.insert()
        is_weekend = lambda day: date(month.timesheet.year, month.timesheet.month, day).weekday() < 5
        hours = lambda day: 8 if is_weekend(day) else None
        code = lambda day: 1 if is_weekend(day) else None
        values = [dict(month_id=month.id, day=day, hours=hours(day), code_id=code(day))
                  for day in range(1, days_in_month+1)]
        Session.execute(i, values)
    